package com.hzdp.handles.rival.processors;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.hzdp.handles.rival.pipelines.DBPipeline;
import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;

import java.util.List;
import java.util.Map;

import static com.hzdp.constant.CommonConstants.*;

/**
 * 京东个护化妆
 * <p/>
 * Created by lyp on 15/12/3.
 */
public class JDProcessor implements PageProcessor {

    static final String START_URL = "http://list.jd.com/list.html?cat=1316%2C1387%2C11932&page=1";
    //static final String START_URL = "http://item.jd.com/323578.html";
    static final String LIST_URL_PATTERN = "http://list\\.jd\\.com/list\\.html\\?cat.+&page=[2-9]";
    static final String LIST_URL_PATTERN2 = "http://list\\.jd\\.com/list\\.html\\?cat.+&page=[1-9]\\d*";

    static final String CONTENT_URL_PATTERN = "http://item.jd.com/\\d+\\.html";
    static final String CONTENT_URL_PATTERN2 = "http://item.jd.hk/\\d+\\.html";
    static final String IMG_URL_PATTERN = "img13\\.360buyimg\\.com/n5/\\d+/.+\\.jpg";

    static final String IMG_PREFX = "img13.360buyimg.com/n1/";

    private final Logger logger = Logger.getLogger(this.getClass());

    @Override
    public void process(Page page) {
        if (page.getUrl().regex(CONTENT_URL_PATTERN).match() || page.getUrl().regex(CONTENT_URL_PATTERN2).match()) {
            rivalData(page);
        } else if(page.getUrl().regex(LIST_URL_PATTERN).match() || page.getUrl().regex(LIST_URL_PATTERN2).match()) {
            rivalLinks(page);
        }
    }

    private void rivalData(Page page) {
        page.putField(SOUCRCE_URL, page.getUrl().regex(CONTENT_URL_PATTERN).toString());
        page.putField(NAME, page.getHtml().css(".m-item-inner").xpath("div[@id='itemInfo']/div").$("h1", "text").toString());
        if(page.getResultItems().get(NAME)==null) {
            page.putField(NAME, page.getHtml().css(".detail-items ").xpath("div[@id='itemInfo']/div").$("h1", "text").toString());
        }
        List<String> imgUrls = page.getHtml().css(".spec-items").css(".lh").$("li").$("img", "data-url").all();
        if(CollectionUtils.isNotEmpty(imgUrls)) {
            List<String> fullImgUrls = Lists.newArrayListWithExpectedSize(imgUrls.size());
            for (String each : imgUrls) {
                fullImgUrls.add(IMG_PREFX + each);
            }
            page.putField(IMG_URLS, fullImgUrls);
        }
        List<String> descList = page.getHtml().css(".p-parameter-list").$("li", "text").all();
        int index = descList.indexOf("品牌： ");
        if(index>=0) {
            descList.remove(index);
        } else {
            //跳过此结果
            page.setSkip(true);
        }

        page.putField(DESCS, hadleDescs(descList));
        page.putField(BRAND_NAME, page.getHtml().css(".p-parameter-list").$("li").$("a", "text").toString());

    }

    private void rivalLinks(Page page) {
        page.addTargetRequests(page.getHtml().css(".p-num").links().regex(LIST_URL_PATTERN).all());
        page.addTargetRequests(page.getHtml().css(".p-num").links().regex(LIST_URL_PATTERN2).all());
        page.addTargetRequests(page.getHtml().css(".gl-warp").links().regex(CONTENT_URL_PATTERN).all());
    }

    private Map<String,String> hadleDescs(List<String> descList) {
        Map<String,String> result = Maps.newHashMap();
        if(CollectionUtils.isEmpty(descList)){
            return result;
        }
        for(String each : descList) {
            String[] split = each.split("：");
            result.put(split[0],split[1]);
        }
        return result;
    }

    @Override
    public Site getSite() {
        return Site.me().setRetryTimes(3).setSleepTime(100);
    }

    public static void main(String[] args) {
        Spider.create(new JDProcessor()).addUrl(START_URL).addPipeline(new DBPipeline(1,"香水")).run();
    }
}
